<?php
/**
 * Created by PhpStorm.
 * User: zhangqipu
 * Date: 2017/11/7
 * Time: 14:08
 */

namespace ApigilityCoupon\Service;


use ApigilityCoupon\DoctrineEntity\Coupon;
use Zend\ServiceManager\ServiceManager;
use Zend\Hydrator\ClassMethods as ClassMethodsHydrator;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrineToolPaginator;
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as DoctrinePaginatorAdapter;

class CouponService
{
    protected $classMethodsHydrator;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    public function __construct(ServiceManager $services)
    {
        $this->classMethodsHydrator = new ClassMethodsHydrator();
        $this->em = $services->get('Doctrine\ORM\EntityManager');
    }

    public function createCoupon($data)
    {
        $cnt = 0;
        $temp = array();
        $data = null;
        $coupons[] = array();
        $maxnum = 50;
        if (isset($data->count)) {
            $maxnum = $data->count;
        }
        while($cnt < $maxnum){
            $temp[] = mt_rand(10000,99999);
            $data = array_unique($temp);
            $cnt = count($data);
        }

        for ($i = 0; $i < count($data); $i++) {
            $coupon = new Coupon();
            $coupon->setCode($data[$i]);
            $coupon->setCreateTime(new \DateTime());
            $coupon->setValidity(10);

            $this->em->persist($coupon);
            $this->em->flush();

            $coupons[$i] = $coupon;
        }

        $coup = new Coupon();
        $coup->setId(1);
        $coup->setCode(123456);
        $coup->setCreateTime(new \DateTime());
        $coup->setValidity(10);

        return $coup;
    }

    public function getCoupon($id) {
        //$coupon = new Coupon();
        $coupon = $this->em->find('ApigilityCoupon\DoctrineEntity\Coupon', $id);
        if (empty($coupon)) {
            throw new \Exception('不存在', 404);
        }

        return $coupon;
    }

    public function getCoupons($params) {
        $qb = new QueryBuilder($this->em);

        if (isset($params->code)) {
            $qb->select('c')
                ->from('ApigilityCoupon\DoctrineEntity\Coupon', 'c')
                ->where('c.code = :code')
                ->setParameter('code', $params->code);

            $doctrine_paginator = new DoctrineToolPaginator($qb->getQuery());
            return new DoctrinePaginatorAdapter($doctrine_paginator);
        }

        $qb->select('c')
            ->from('ApigilityCoupon\DoctrineEntity\Coupon', 'c');

        $doctrine_paginator = new DoctrineToolPaginator($qb->getQuery());
        return new DoctrinePaginatorAdapter($doctrine_paginator);
    }
}